package com.liuyang.demo.threadPool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class ThreadExtend_Pool_Return_Value {
    public static void main(String args[]) throws ExecutionException, InterruptedException {
        //创建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        //创建有两个返回值的线程
        Callable callable1 = new CallableImpl("callable1");
        Callable callable2 = new CallableImpl("callable2");
        //执行任务并获取future对象
        Future future1 = executorService.submit(callable1);
        Future future2 = executorService.submit(callable2);
        log.info("一：{}");

        //从future获取返回值，并输出到控制台
        System.out.println(">>>>" + future1.get().toString());
        log.info("二：{}");

        System.out.println(">>>>" + future2.get().toString());
        log.info("三：{}");

        //关闭线程池
        executorService.shutdown();
    }
}

/**
 * 有返回值的线程需要实现Callable接口
 */
class CallableImpl implements Callable {
    private String oid;

    CallableImpl(String oid) {
        this.oid = oid;
    }

    @Override
    public Object call() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return this.oid + "任务返回的内容";
    }
}
